package com.ycyoes.demos.netty.demo;

import com.ycyoes.demos.netty.demo.handler.ClientHandler;
import com.ycyoes.demos.netty.demo.handler.FirstClientHandler;
import com.ycyoes.utils.DateUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class NettyClient {
    public static final Integer MAX_RETRY = 10;

    public static void main(String[] args) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workGroup)               //1. 指定线程模型
                .channel(NioSocketChannel.class) //2. 指定IO类型为NIO
                .handler(new ChannelInitializer<SocketChannel>() {  //3. IO处理逻辑
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(new FirstClientHandler());
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });
        //4. 建立连接
        /*bootstrap.connect("juejin.cn", 80).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功！");
            } else {
                System.out.println("连接失败！");
            }
        });*/
        connect(bootstrap, "127.0.0.1", 8001, MAX_RETRY);
    }

    private static void connect(Bootstrap bootstrap, String host, int port, final int retry) {
        System.out.println("retry: " + retry);
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功！");
            } else if(retry == 0) {
                System.err.println("重试次数已用完，放弃连接！");
            }
            else {
                //第几次重连
                int order = (MAX_RETRY - retry) + 1;
                //本次重连的间隔
                int delay = 1 << order;
                System.err.println(new Date() + ": 连接失败，第" + order + "次重连！" + DateUtils.formatDateTime(new Date()));
                int retryAfter = retry - 1;
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retryAfter), delay, TimeUnit.SECONDS);
            }
        });
    }


}
